<template>
  <BasicModal width="700" v-bind="$attrs" cancelText="关闭" okText="提交"
    :title="getTitle"
    :canFullscreen="false"
    :centered="true"
    :destroyOnClose="true"
    :maskClosable="false"
    :okButtonProps="{ disabled: isUploadingRef }"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" :model="model"/>
  </BasicModal>
</template>

<script lang="ts" setup>
  import {ref, computed, unref, reactive} from 'vue';
  import {BasicModal, useModalInner} from '/@/components/Modal';
  import {BasicForm, useForm} from '/@/components/Form/index';
  import {formSchema} from '../Affiche.data';
  import {filterObj} from '/@/utils/common/compUtils';
  import {saveOrUpdate, queryById} from '../Affiche.api';
  // Emits声明
  const emit = defineEmits(['register','success']);
  const isUpdate = ref(true);
  // 表单modal
  const model = reactive<any>({})
  // 是否正在上传
  const isUploadingRef = ref(false);

  //设置标题
  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  //表单配置
  const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  //表单赋值
  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    //重置表单
    await resetFields()
    setModalProps({confirmLoading: false, showCancelBtn:data?.showFooter, showOkBtn:data?.showFooter});
    isUpdate.value = !!data?.isUpdate;

    let record = data?.record || {}
    if (isUpdate.value) {
      record = await queryById({id: record?.id});
      Object.assign(model, record);
    } else {
      model.length = 0;
      Object.assign(model, {});
    }
    await setFieldsValue(record)
  });

  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      setModalProps({confirmLoading: true});
      //提交表单
      values.attachments = '';
      await saveOrUpdate(filterObj(values), isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success', {isUpdate: isUpdate.value, values});
    } finally {
      setModalProps({confirmLoading: false});
    }
  }
</script>

<style lang="less" scoped>
  :deep(.ant-input-number .ant-input-number-input) {
    padding: 0 3px !important;
  }
  :deep(.ant-input-affix-wrapper) {
    padding: 0px !important;
  }
  :deep(.ant-input-affix-wrapper .ant-input-suffix) {
    margin-right: 7px;
  }
</style>